package DBWrapper::CrawlerManager;

# $Id: CrawlerManager.pm 255 2010-07-17 14:40:11Z dolbanavt $
# $Date: 2010-07-17 17:40:32 +0300 (Суб, 17 Июл 2010) $
# $HeadURL: https://robosearch.googlecode.com/svn/branches/reborn/lib/DBWrapper/CrawlerManager.pm $
# $LastChangedRevision: 351 $

use parent qw( DBWrapper );
use JIP::ToolSet;
use Carp qw( croak );
use English qw( -no_match_vars );
use Host;

our $VERSION = '1.0';

sub get_hosts_for_indexing {
    my ( $self, $ageing ) = @ARG;

    croak 'ageing required' unless defined $ageing;

    my $statement = $self->get_dbh->prepare( q{
        SELECT
            hosts.id         AS host_identifier,
            hosts.ip_address AS host_ip_address
        FROM
            hosts
            INNER JOIN
            (
                SELECT   host_id, MAX( last_scan ) AS date_of_last_scan
                FROM     network_scans
                GROUP BY host_id
            ) AS last_scans ON hosts.id = last_scans.host_id
            INNER JOIN
            (
                SELECT   host_id, MAX( last_crawl ) AS date_of_last_crawl
                FROM     crawls
                GROUP BY host_id
            ) AS last_crawls ON hosts.id = last_crawls.host_id
        WHERE
            last_scans.date_of_last_scan   < SUBDATE( NOW(), INTERVAL ? HOUR )
            AND
            last_crawls.date_of_last_crawl > SUBDATE( NOW(), INTERVAL ? HOUR )
    } ) or croak 'cannot prepare: '. $self->get_dbh->errstr;

    $statement->execute( $ageing, $ageing )
        or croak 'cannot execute: '. $self->get_dbh->errstr;

    my @hosts;

    while ( my $ln = $statement->fetchrow_hashref() ) {
        push @hosts, Host->new(
            host_id    => $ln->{'host_identifier'},
            ip_address => $ln->{'host_ip_address'},
        );
    }

    return @hosts;
}

sub update_status_for {
    my ( $self, $host_id ) = @ARG;

    croak 'host_id required' unless defined $host_id;

    $self->get_dbh->do(
        q{INSERT INTO crawls ( host_id, last_crawl ) VALUES ( ?, NOW() )},
        {},
        $host_id,
    ) or croak 'cannot insert data: '. $self->get_dbh->errstr;

    return 1;
}

1;

__END__

=head1 NAME

DBWrapper::CrawlerManager - обертка над базой данный для
менеджера краулеров

=head1 SYNOPSIS

    use DBWrapper::CrawlerManager;

    my $w = DBWrapper::CrawlerManager->new( dbh => DBI->new() );

=head1 DEPENDENCIES

JIP::ToolSet (from base_lib)

=head1 AUTHOR

Vladimir Zhavoronkov, <dolbanavt (at) Google Mail>

http://dolbanavt.livejournal.com/

=head1 LICENSE AND COPYRIGHT

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

=cut
